﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure;
using System.Configuration;

public partial class AccountSettings : System.Web.UI.Page
{
    string imgLocation; //locate image in database

    protected void Page_Load(object sender, EventArgs e)
    {
        string strConnString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; //connection string to database
        SqlConnection Connection = new SqlConnection(strConnString); //set connectionstring to sqlconnection

        Session["ConnDB"] = Connection;
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        string SqlQuery; 

        MembershipUser user = Membership.GetUser(); //get user from membership
        SqlQuery = "SELECT profileImage FROM userTable where userName ='" + user.UserName + "';"; //select the image from currentuser
        SqlCommand cmd = new SqlCommand(SqlQuery, Connection); //establish new sqlcommand
        Connection.Open(); //open connection
        SqlDataReader Reader = cmd.ExecuteReader(); //execture sql command set it to reader
        while (Reader.Read()) //as long as the reader has content , do this
        {
            imgLocation = Reader[0] as string; //locate the imagelocation and set it to string, because Reader only finds one entry we can use Reader[0]
        }
        Connection.Close(); //close connection to database
        profilePic.ImageUrl = imgLocation; //set imagebuttons image with the location of image

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString);  //connection string to the container
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); //creates the blob service client
        var properties = blobClient.GetServiceProperties(); //get properties so we can change them
        properties.DefaultServiceVersion = "2012-02-12"; //set to version
        blobClient.SetServiceProperties(properties); //add new properties
        Session["blobClient"] = blobClient;
    }

    protected void profileButton_Click(object sender, EventArgs e)
    {
        string fileName = pictureUploader.FileName;
        if(fileName == null) {
            Response.Redirect("AccountSettings.aspx");
        }

        CloudBlobClient blobClient = (CloudBlobClient)Session["blobClient"];
        CloudBlobContainer container = null;
        CloudBlockBlob blockBlob = null;
        container = blobClient.GetContainerReference("profile-images"); //set container to profile-images container
        blockBlob = container.GetBlockBlobReference(fileName); //set blockblob to the fileuploader file
        string place = "http://educenterstorage.blob.core.windows.net/profile-images/"; //place image in this container
        place += fileName; //add to the container the name of the file
        MembershipUser user = Membership.GetUser(); //get current user
        using (var fileStream = pictureUploader.FileContent) // Uploading the image file
        {
            blockBlob.UploadFromStream(fileStream); //create stream to upload the image to storage
        }
        SqlConnection Connection = (SqlConnection)Session["ConnDB"]; //start connection
        string SqlQuery = "UPDATE UserTable SET profileImage = '" + place + "' WHERE " + "userName = '" + user.UserName + "';"; //query to update the database to include the profile image location of current user
        SqlCommand cmd = new SqlCommand(SqlQuery, Connection); //create new command

        Connection.Open(); //open connection to database
        cmd.ExecuteNonQuery(); //execute the command
        Connection.Close(); //close connection to database
        profilePic.ImageUrl = imgLocation; //set the profile picture imagebutton to this source

  //      EduLogger.logActivity(User.Identity.Name, "changed picture", HttpContext.Current.Request.Url.AbsoluteUri);

        Response.Redirect("AccountSettings.aspx");  //refresh page to show the new image

    }
    protected void changeEmail_Click(object sender, EventArgs e)
    {
        MembershipUser user = Membership.GetUser(); //get current user
        user.Email = emailTextbox.Text; //reference to the new email
        Membership.UpdateUser(user); //update user to the new email

 //       EduLogger.logActivity(User.Identity.Name, "changed email", HttpContext.Current.Request.Url.AbsoluteUri);
    }
    protected void changeCardButton_Click(object sender, EventArgs e)
    {
        MembershipUser user = Membership.GetUser(); //get current user
        string cardHolder = cardHolderBox.Text;
        string cardType = cardTypeList.SelectedValue;
        string creditNumber = creditCardNumberBox.Text;
        string expireYear = expireYearList.SelectedValue;
        string expireMonth = expireMonthList.SelectedValue;
        string cvc = cvcBox.Text;
        DateTime expiry = new DateTime(Convert.ToInt32(expireYearList.SelectedValue), Convert.ToInt32(expireMonthList.SelectedValue), 1);

        SqlConnection Connection = (SqlConnection)Session["ConnDB"];
        string SqlQuery = "INSERT INTO cardPaymentTable VALUES(@cardNumber,@cardType,@cardHolder,";
        SqlQuery = SqlQuery + "@date, @cvc, @user);"; //add new record info

        SqlCommand cmd = new SqlCommand(SqlQuery, Connection);

        cmd.Parameters.AddWithValue("@cardNumber", creditNumber);
        cmd.Parameters.AddWithValue("@cardType", cardType);
        cmd.Parameters.AddWithValue("@cardHolder", cardHolderBox.Text);
        cmd.Parameters.AddWithValue("@date", expiry);
        cmd.Parameters.AddWithValue("@cvc", cvc);
        cmd.Parameters.AddWithValue("@user", user.UserName);

        Connection.Open(); //open connection to database
        cmd.ExecuteNonQuery(); //execute the command
        Connection.Close(); //close connection to database

   //     EduLogger.logActivity(User.Identity.Name, "changed card", HttpContext.Current.Request.Url.AbsoluteUri);
    }
    protected void changePassButton_Click(object sender, EventArgs e)
    {
        MembershipUser user = Membership.GetUser(); //get current user
        user.ChangePassword(oldPasswordBox.Text, newPasswordBox.Text); //change password of current user by replaceing the old password with the new one
        Membership.UpdateUser(user); //update new information

        //EduLogger.logActivity(User.Identity.Name, "changed password", HttpContext.Current.Request.Url.AbsoluteUri);
    }

    protected void deleteButton_Click(object sender, EventArgs e)
    {
        MembershipUser user = Membership.GetUser(); //get current user

   //     EduLogger.logActivity(User.Identity.Name, "deleted user", HttpContext.Current.Request.Url.AbsoluteUri);
        SqlConnection Connection = (SqlConnection)Session["ConnDB"];
        string SqlQueryUser = "DELETE FROM userTable where userName ='" + user.UserName + "';";  //Delete user from userTable
        string SqlQueryCard = "DELETE FROM cardPaymentTable where userName ='" + user.UserName + "';"; //Delete user from cardPaymentTable


        SqlCommand cmdUser = new SqlCommand(SqlQueryUser, Connection); 
        SqlCommand cmdCard = new SqlCommand(SqlQueryCard, Connection); //establish new sqlcommand
        Connection.Open(); //open connection

        cmdUser.ExecuteNonQuery();
        cmdCard.ExecuteNonQuery(); //execute deletion

        Connection.Close();

        FormsAuthentication.SignOut(); //log out user
        HttpContext.Current.Session.Clear(); //clear the current session of user
        System.Web.Security.Membership.DeleteUser(user.UserName, true); //delete user
        Response.Redirect("Homescreen.aspx"); //return the deleted user to homescreen
    }
}